package com.plusmoney.approval.customer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.common.Constants;
import com.mp.approvalreq.service.*;
import com.mp.approvalreq.util.ListHelper;
import com.mp.approvalreq.util.MailUtils;
import com.mp.user.entity.User;
import com.mp.user.service.UserServicePrx;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.mq.MQUtils;
import com.plusmoney.redis.RedisUtils;
import com.plusmoney.util.Utils;
import com.qq.tars.client.util.ServantUtils;
import org.apache.log4j.NDC;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.util.*;


public class UserListener implements MessageListenerConcurrently {

	private static final Logger logger = LoggerFactory.getLogger(UserListener.class);

	@Override
	public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
		try {
			Jedis jedis = RedisUtils.getJedis();

			for (MessageExt msg : list) {
				NDC.push(Utils.getNDCMessage());
				if ("UserSignIn".equals(msg.getTags())||"UserSignOut".equals(msg.getTags())) {
					NDC.pop();
					continue;
				}
				logger.info("msgId:{}, tags:{}, keys:{}, body:{}",
						msg.getMsgId(), msg.getTags(), msg.getKeys(), new String(msg.getBody()));

				String redisKey = RedisUtils.getKey(Constants.MQ_GROUP_NAME, Constants.MQ_APPROVAL_TOPIC, msg.getMsgId());
				if (!MQUtils.isNewMessage(jedis, redisKey)) {
					logger.info("消息重复");
					NDC.pop();
					continue;
				}

				if (Objects.equals(Constants.MQ_TAGS_USER_DIMISSION, msg.getTags())) {
					handleQuitUser(msg);
				} else if (Objects.equals(Constants.MQ_TAGS_COMPANY_CREATE, msg.getTags())) {
					JSONObject jsonObject = JSON.parseObject(new String(msg.getBody()));
					handleCreateCompany(jsonObject.getInteger("companyId"));
				}

				NDC.pop();
			}

			RedisUtils.close(jedis);
			return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
		} catch (Throwable e) {
			logger.error(e.getMessage(), e);
			throw new RpcServerLogicalException(1, "报错了");
		}
	}

	private void handleCreateCompany(Integer companyId) {
		try {
			SelectApprovalServicePrx selectApprovalService = ServantUtils.getObject(SelectApprovalServicePrx.class);
			selectApprovalService.initGlobalSetting(companyId);

			ApprovalOperateServicePrx approvalOperateService = ServantUtils.getObject(ApprovalOperateServicePrx.class);
			approvalOperateService.initDefaultTemplate(companyId);
		} catch (Throwable e) {
			logger.error(e.getMessage(), e);
			MailUtils.sendMail(MailUtils.EMAIL, String.format("新公司(%d)初始化审批模板/全局设置错误", companyId), e.getMessage());
		}
	}


	private void handleQuitUser(MessageExt msg) {
		try {
			UserServicePrx userService = ServantUtils.getObject(UserServicePrx.class);

			User user = JSONObject.parseObject(msg.getBody(), User.class);
			user = userService.getUserByContactId(user.getContactId());

			GeneralRequestServicePrx generalRequestServicePrx = ServantUtils.getObject(GeneralRequestServicePrx.class);
			TemplateServicePrx templateServicePrx = ServantUtils.getObject(TemplateServicePrx.class);

			generalRequestServicePrx.handQuitUser(user);
			templateServicePrx.handleQuitTemplate(user);

			// 用户的多身份列表为空才表示离职,否则有可能只是身份删除
			if (ListHelper.isNotNullEmpty(user.getMultiContactIdList())) {
				return;
			}

			RequestServicePrx requestServicePrx = ServantUtils.getObject(RequestServicePrx.class);

			requestServicePrx.handleQuitRequestFlow(user);
			requestServicePrx.handleQuitRequestCc(user);

		} catch (Throwable e) {
			logger.error(e.getMessage(), e);
			MailUtils.sendMail(MailUtils.EMAIL, "审批离职程序错误", e.getMessage());
		}
	}


}
